package gui;

import java.util.ArrayList;
import java.util.List;

import org.Consts;
import org.Globals;
import org.Utility;
import org.json.JSONException;
import org.json.JSONObject;

import DTO.GradientsDTO;
import DTO.ObjectDTO;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.ydev.graphics.animations.R;

public class Objects extends Activity {

	private SQLiteDatabase sqlDB = null;

	private LinearLayout layoutImages;

	private ProgressDialog progress;

	List<View> allViews;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.objects);

		progress = new ProgressDialog(Objects.this);
		progress.setMessage("Loading...");
		progress.setIndeterminate(false);
		progress.setCancelable(false);

		

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		setupScreen();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.home, menu);
		return true;
	}

	public void setupScreen() {

		layoutImages = (LinearLayout) findViewById(R.id.linearLayoutImages);

		if (!progress.isShowing())
			progress.show();

		new Thread(new Runnable() {

			@Override
			public void run() {

				allViews = new ArrayList<View>();
				/*ArrayList<ObjectDTO> imageList = ObjectDTO
						.getObjectsInDatabase(Globals.sqlDB);*/
				ArrayList<ObjectDTO> imageList = ObjectDTO
						.getObjectsInDatabase(Globals.sqlDB);

				Log.d("", "== image list is:" + imageList);

				LinearLayout imageLayout = new LinearLayout(Objects.this);
				imageLayout.setOrientation(LinearLayout.HORIZONTAL);
				imageLayout.setLayoutParams(new LinearLayout.LayoutParams(
						LinearLayout.LayoutParams.WRAP_CONTENT,
						LinearLayout.LayoutParams.WRAP_CONTENT));

				if (imageList != null) {

					for (int i = 0; i < imageList.size(); i++) {
						Log.d("", "=* image list size is: " + imageList.size());

						allViews.add(inflateContents(imageList.get(i), i));
					}

				} else {
					Log.d("", "== image list was null");
				}

				Log.d("", "== child count: " + layoutImages.getChildCount());
				imageLayout = null;

				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						try {

							if (layoutImages.getChildCount() > 0)
								layoutImages.removeAllViews();

							Display display = getWindowManager()
									.getDefaultDisplay();
							int maxWidth = display.getWidth();

							LinearLayout newLL = new LinearLayout(Objects.this);
							newLL.setLayoutParams(new LayoutParams(
									LayoutParams.FILL_PARENT,
									LayoutParams.WRAP_CONTENT));
							newLL.setGravity(Gravity.LEFT);
							newLL.setOrientation(LinearLayout.HORIZONTAL);

							int widthSoFar = 0;
							int imageSize = maxWidth / 4 - 3;
							LayoutParams lp = new LayoutParams(imageSize,
									imageSize);

							for (int i = 0; i < allViews.size(); i++) {

								allViews.get(i).measure(0, 0);

								widthSoFar += imageSize;// allViews.get(i).getMeasuredWidth();

								Log.d("",
										"== widthSoFar is "
												+ String.valueOf(widthSoFar));
								Log.d("",
										"== maxWidth is "
												+ String.valueOf(maxWidth));
								if (widthSoFar > maxWidth) {
									layoutImages.addView(newLL);
									Log.d("", "== a new row");

									newLL = new LinearLayout(Objects.this);
									newLL.setLayoutParams(new LayoutParams(
											LayoutParams.FILL_PARENT,
											LayoutParams.WRAP_CONTENT));
									newLL.setOrientation(LinearLayout.HORIZONTAL);
									newLL.setGravity(Gravity.LEFT);

									widthSoFar = 0;

									newLL.addView(allViews.get(i), lp);

									allViews.get(i).measure(0, 0);
									widthSoFar += allViews.get(i)
											.getMeasuredWidth();
								} else {
									newLL.addView(allViews.get(i), lp);
								}
							}

							layoutImages.addView(newLL);

							/*
							 * if (allViews != null) { int i = 0; for (View v :
							 * allViews) { i += 1; layoutImages.addView(v);
							 * Log.d("", "== added view: " + String.valueOf(i));
							 * }
							 * 
							 * Log.d("", "== added all views, size:" +
							 * allViews.size()); }
							 */

							if (progress.isShowing())
								progress.dismiss();
						} catch (Exception ex) {
							ex.printStackTrace();
						}
					}

				});
			}

		}).start();

	}

	public View inflateContents(final ObjectDTO obj, final int index) {

		LayoutInflater inflater = (LayoutInflater) getApplicationContext()
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		final View cell = inflater.inflate(R.layout.gallery_cell, null, true);

		ImageView imgPicture = (ImageView) cell
				.findViewById(R.id.imgSmallPicture);

		if (obj != null) {
			imgPicture.setImageBitmap(obj.image);
		} else {
			imgPicture.setImageDrawable(Utility.getDrawable(
					getApplicationContext(), R.drawable.no_photo, false));
		}

		cell.setLayoutParams(new LinearLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

		JSONObject tag = new JSONObject();
		try {
			tag.put(Consts.COLUMN_OBJECT_ID, obj.intUuid);
			
			tag.put("isSelected", "false");
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		cell.setTag(tag.toString());

		cell.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				ImageView imgCheckbox = (ImageView) cell
						.findViewById(R.id.imgCheckbox);
				JSONObject tag = null;
				try {
					tag = new JSONObject((String) cell.getTag());
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				if (tag.opt("isSelected").equals("true")) {
					try {
						tag.put("isSelected", "false");
						imgCheckbox.setVisibility(View.GONE);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} else {
					try {
						tag.put("isSelected", "true");
						imgCheckbox.setVisibility(View.VISIBLE);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				cell.setTag(tag.toString());
				/*
				 * Log.d("", "== image is selected"); Intent intent = new
				 * Intent(Objects.this, AddEditObjects.class);
				 * intent.putExtra(Consts.DTO_PK, index+1);
				 * startActivity(intent);
				 */

			}
		});
		
		cell.setOnLongClickListener(new View.OnLongClickListener() {

			@Override
			public boolean onLongClick(View v) {
				JSONObject tag = null;
				try {
					tag = new JSONObject((String) cell.getTag());
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				int object_id = tag.optInt(Consts.COLUMN_OBJECT_ID);
				Intent intent = new Intent(Objects.this, AddEditObjects.class);
				intent.putExtra(Consts.DTO_PK, object_id);
				startActivity(intent);
				return true;
			}

		});

		return cell;
	}

	public void newClicked(View v) {
		Intent intent = new Intent(Objects.this, AddEditObjects.class);
		intent.putExtra(Consts.DTO_PK, -1);
		startActivity(intent);
	}

	public void addClicked(View v) {
		Intent intent = new Intent(Objects.this, AndroidExplorer.class);
		// intent.putExtra(Consts.DTO_PK, -1);
		startActivity(intent);
	}

	public void editClicked(View v) {
		Intent intent = new Intent(Objects.this, AddEditObjects.class);
		intent.putExtra(Consts.DTO_PK, -1);
		startActivity(intent);
	}

	public void deleteClicked(View v) {
		ArrayList<View> selected = new ArrayList<View>();
		findSelected(selected);
		ObjectDTO obj = null;
		JSONObject tag = null;
		for (View cell : selected) {
			try {
				tag = new JSONObject((String) cell.getTag());
				int pk=(Integer) tag.opt(Consts.COLUMN_OBJECT_ID);
				obj = new ObjectDTO(pk, Globals.sqlDB);
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			obj.delete(Globals.sqlDB);
			
		}
		setupScreen();
	}

	public void findSelected(ArrayList<View> selected) {
		for (View cell : allViews) {
			JSONObject tag = null;
			try {
				tag = new JSONObject((String) cell.getTag());
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (tag.opt("isSelected").equals("true")) {
				selected.add(cell);
			}
		}
	}

}
